package com.shop.goods.listener;

import com.alibaba.fastjson.JSONObject;
import com.shop.domain.Order;
import com.shop.domain.Task;
import com.shop.goods.config.RabbitMqConfig;
import com.shop.goods.service.ProductDetailsService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
@Component
public class OrderListener {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ProductDetailsService productDetailsService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @RabbitListener(queues = RabbitMqConfig.ORDER_QUEUE)
    public void reducedInventory(String message){
        //格式转换
        Task task = JSONObject.parseObject(message, Task.class);
        //判断redis中是否存在
        Object o = redisTemplate.opsForValue().get(task.getId());
        if(o != null){
            //若存在，没有操作
            return;
        }
        // 不存在，存入redis 过期时间5min
        redisTemplate.opsForValue().set(task.getId(), task.getId(),5, TimeUnit.MINUTES);
        //减库存
        Order order = JSONObject.parseObject(task.getRequestBody(), Order.class);

        Integer i = productDetailsService.reduceStock(order.getProductId(), order.getNum());
        if(i != 1){
            //库存不足 发消息给订单服务，
            rabbitTemplate.convertAndSend(RabbitMqConfig.ORDER_EXCHANGE,RabbitMqConfig.ORDER_FAIL_QUEUE,order.getId());
        }
        // 减库存成功 发消息给order 删除task中数据
        rabbitTemplate.convertAndSend(RabbitMqConfig.TASK_EXCHANGE,RabbitMqConfig.TASK_QUEUE,task.getId());
    }

    @RabbitListener(queues = RabbitMqConfig.ADD_QUEUE)
    public void addReducedInventory(String message) {
        Order order = JSONObject.parseObject(message, Order.class);
        Integer i = productDetailsService.reduceStock(order.getProductId(), -order.getNum());
        if(i != 1){
            //抛异常 会一直重试加库存 消息不会被消费掉
            throw new RuntimeException("加库存失败");
        }
    }
}
